<%@ page  import="java.io.FileInputStream" %>
<%@ page  import="java.io.BufferedInputStream"  %>
<%@ page  import="java.io.File"  %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.util.Set" %>
<%@ page import="serverDB.*" %>

<%
	String filePath;
	Set<serverDB.File> files = (Set<serverDB.File>)session.getAttribute("files");
	int fileId = Integer.parseInt(request.getParameter("id"));
	serverDB.File theFile =null;
	int i=0;
	for(serverDB.File f : files){
		if(i==fileId){
			theFile=f;
			break;
		}
		i++;
	}
	filePath=theFile.getFileLocation();
	BufferedInputStream buf=null;
   	ServletOutputStream myOut=null;

	try{

		myOut = response.getOutputStream( );
	    File myfile = new File(filePath);
	     
	     //set response headers
	    response.setContentType("text/plain");
	     
	    response.addHeader("Content-Disposition","attachment; filename="+theFile.getFileName() );
	
	    response.setContentLength( (int) myfile.length( ) );
	     
	    FileInputStream input = new FileInputStream(myfile);
	    buf = new BufferedInputStream(input);
	    int readBytes = 0;
	
	    //read from the file; write to the ServletOutputStream
	    while((readBytes = buf.read( )) != -1)
	      myOut.write(readBytes);

	} catch (IOException ioe){
     
    	throw new ServletException(ioe.getMessage( ));
         
    } finally {
         
     //close the input/output streams
         if (myOut != null)
            myOut.close( );
         if (buf != null)
         	buf.close( );
         
    }

   
   
%>